import java.util.Arrays;

public class Solution105 {

    private int getValInd(int[] inorder, int val){
        for (int i = 0; i < inorder.length; i++) {
            if(inorder[i] == val){
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int length = preorder.length;
        if(length == 0){ return null; }
        int tmpVal = preorder[0], valInd = getValInd(inorder, tmpVal), valIndNext = valInd + 1;
        TreeNode tmpNode = new TreeNode(tmpVal);
        tmpNode.left = buildTree(Arrays.copyOfRange(preorder, 1, valIndNext),
                                 Arrays.copyOfRange(inorder, 0, valInd));
        tmpNode.right = buildTree(Arrays.copyOfRange(preorder, valIndNext, length),
                                  Arrays.copyOfRange(inorder, valIndNext, length));
        return tmpNode;
    }
}
